﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using PowerCreator.LMS.DL.Project.Entity;
using PowerCreator.LMS.Web.DL.Project;
using PowerCreator.LMS.Common.Script;

public partial class sysadmin_DL_Project_ClassRank : PowerCreator.LMS.Web.Base.WebBasePage
{
    TOClass objClass = new TOClass();
    PowerCreator.LMS.ViewQuery.ViewQuery obj = new PowerCreator.LMS.ViewQuery.ViewQuery();
    private PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
   // private string url = "../../login.aspx";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitPage();
            string search = GetSearch();
            BinderPager(search);
            BinderPG(search, 1);
        }

    }
    protected override void InitPage()
    {
        base.InitPage();
    }
    private string GetSearch()
    {
        string search = "SELECT TO_Class.Class_Id,TO_Class.Name,  TO_CourseList.CourseListName, TO_Class.Broswer, TO_Class.ClassAssistant, TO_Class.ClassLeader,  TO_Class.ClassLecturer,TO_CourseList.CourseID FROM TO_Class ,TO_CourseList Where TO_Class.ClassCourseListID = TO_CourseList.CourseList_Id";
        //if (!string.IsNullOrEmpty(txt_KeyWord.Text))
            //search += string.Format(" and Name like '%{0}%'", txt_KeyWord.Text.Trim());
        //search += System.String.Format(" and TO_Class.Class_Id in (Select FkOID from TauthorityUser as a , TauthorityList as b where a. FkAuthorityID = b.FkAuthorityID and FkUserID ={0} and b.authorityType=2)", GetLoginEntity.UserID);
        return search;
    }

    protected void BinderPager(string search)
    {
        AspNetPager1.RecordCount = obj.Count(search);
        AspNetPager1.PageSize = obj.Count(search);
    }
    private void BinderPG(string search, int pageIndex)
    {
        double intscoresStuCou = 0;
        double intscoresStu = 0;
        double intScoresCls = 0;
        double douAvgScoresCls = 0;
        double douScoreP = 0;
        string orderby = " Class_Id Desc";
        DataTable dt = obj.Query(search, orderby, LMSPageSize, pageIndex);//所有班级

        PowerCreator.LMS.ViewQuery.ViewQuery objView = new PowerCreator.LMS.ViewQuery.ViewQuery();
        string searchView = "";
        dt.Columns.Add("StrState");
        dt.Columns.Add("avgScore",typeof(float));
        dt.Columns.Add("levelClass");
        dt.Columns.Add("Batch");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strClsCourseID = dt.Rows[i]["CourseID"].ToString();
            string[] strCourseIDA = strClsCourseID.Split(',');
            //得到班级批次
            string searchBatch = "select a.Batch_Id,Batch from TO_Batch as a ,TO_CourseList as b ,to_class as c where a.Batch_Id =b.Batch_Id and b.CourseList_Id = c.ClassCourseListID and c.Class_Id={0}";
            DataTable dtBatch = objView.Query(string.Format(searchBatch, dt.Rows[i]["Class_Id"].ToString()));
            string strBatch = dtBatch.Rows[0]["Batch"].ToString();
            string strBatchID = dtBatch.Rows[0]["Batch_Id"].ToString();
            //得到每个班的学员
            string searchUser = "SELECT TO_UserOfClass.UserID FROM TO_Learner ,TO_UserOfClass where TO_Learner.Learner_Id = TO_UserOfClass.UserID and TO_UserOfClass.ClassID=" + dt.Rows[i]["Class_Id"].ToString();
            DataTable dtUser = objView.Query(searchUser);
            for (int m = 0; m < dtUser.Rows.Count; m++)
            {
                for (int n = 0; n < strCourseIDA.Length; n++)
                {
                    //截取课程id 和 学分 ,0为课程ID，1为学分
                    string[] strCourseIDB = strCourseIDA[n].Split('#');

                    string seacherInfoA = "select * from to_course where course_Id=" + strCourseIDB[0];
                    DataTable dtCourseInfo = objView.Query(seacherInfoA);
                    //得到每个学员每门课的总学时 
                    string searchCourse = "select sum(SscrlogTotalTime) as studyHours,FKSscrlogCourseID from TStudentStudyCouReslog group by FKSscrlogUserID,FKSscrlogTrainclaID,FKSscrlogCourseID having FKSscrlogUserID={0} and FKSscrlogTrainclaID={1} and FKSscrlogCourseID ={2}";
                    searchView = string.Format(searchCourse, dtUser.Rows[n]["UserID"].ToString(), dt.Rows[i]["Class_Id"].ToString(), strCourseIDB[0]);
                    DataTable dtCourse = objView.Query(searchView);
                    //得到作业完成次数
                    string searchWorkNum = "select count(*) as WorkNum,courseID,Creator ,ClassID from (select courseID,a.Creator,ClassID from TO_UserClassTask as a ,TO_ClassTasks as b where a.task_Id =b.ClassTasks_Id) as tb group by courseID,Creator ,ClassID having Creator ={0} and classID ={1} and courseID ={2}";
                    searchView = string.Format(searchWorkNum, dtUser.Rows[n]["UserID"].ToString(), dt.Rows[i]["Class_Id"].ToString(), strCourseIDB[0]);
                    DataTable dtWorkNum = objView.Query(searchView);
                    //得到作业评论次数
                    string searchTasksReply = "select count(*) as ReplyNum ,Creator,ClassID,courseID from (select courseID,b.Creator,ClassID from TO_ClassTasksReply as a ,TO_UserClassTask as b ,TO_ClassTasks as c  where a.UserTask_Id = b.UserTask_Id and b.task_Id = c.ClassTasks_Id ) as tb group by Creator,ClassID,courseID having Creator ={0} and classID ={1} and courseID ={2}";
                    searchView = string.Format(searchTasksReply, dtUser.Rows[n]["UserID"].ToString(), dt.Rows[i]["Class_Id"].ToString(), strCourseIDB[0]);
                    DataTable dtTasksReply = objView.Query(searchView);

                    //string strCourseID = dtCourse.Rows[0]["FKSscrlogCourseID"];
                    //得到考试成绩
                    string searchExam = "select * from UserPaperHistory where fKUPHistoryClassID={0} and fKUPHistoryUserID ={1} and fKUPHistoryCourseID={2}";
                    searchView = string.Format(searchExam, dt.Rows[i]["Class_Id"].ToString(), dtUser.Rows[n]["UserID"].ToString(), strCourseIDB[0]);
                    DataTable dtExam = objView.Query(searchView);
                    //得到规则
                    string searchRuleList = "select top 1 isnull(TotalTime_Low,0) as TotalTime_Low,isnull(TotalTime_High,0) as TotalTime_High,	isnull(TotalTimeWeightA,0) as TotalTimeWeightA,isnull(WorkFinishTimes_Low,0) as WorkFinishTimes_Low,isnull(WorkFinishTimes_High,0) as WorkFinishTimes_High,isnull(WorkFinishTimesWeightB,0) as WorkFinishTimesWeightB,isnull(WorkCommentTimes_Low,0) as WorkCommentTimes_Low,isnull(WorkCommentTimes_High,0) as WorkCommentTimes_High,isnull(WorkCommentTimesWeightB,0) as WorkCommentTimesWeightB,isnull(WorkTatolWeigthA,0) as WorkTatolWeigthA,isnull(Score_Low,0) as Score_Low,isnull(Score_High,0) as	Score_High,isnull(ScoreWeightA,0) as ScoreWeightA from TO_FormulaOfRule as a,to_rule as b where b.Rule_ID = a.RuleID and FKBatchID ={0} and FKCourseID={1}";
                    searchView = string.Format(searchRuleList, strBatchID, strCourseIDB[0]);
                    DataTable dtRuleList = objView.Query(searchView);
                    //计算平均成绩使用的变量
                    double intHours = 0;
                    double intTotalTimeWeightA = 0;
                    double TotalTime_Low = 0;
                    double TotalTime_High = 0;
                    double intScoresHours = 0;

                    double intworkFinishTimes = 0;
                    double intFinishTimesWeightB = 0;
                    double WorkFinishTimes_Low = 0;
                    double intWorkScores = 0;
                    double WorkFinishTimes_High = 0;


                    double intTasksReply = 0;
                    double workCommentTimesWeightB = 0;
                    double WorkCommentTimes_Low = 0;
                    double WorkCommentTimes_High = 0;
                    double intScoresComment = 0;

                    double intworkTatolWeightA = 0;
                    double intExam = 0;
                    double intScoreWeightA = 0;
                    double Score_Low = 0;
                    double Score_High = 0;
                    double intScoresExam = 0;

                    //如果没有设置，那么不去计算
                    if (dtCourse.Rows.Count > 0 && dtRuleList.Rows.Count > 0)
                    {
                        //计算每个学员每门课的学分
                        intHours = int.Parse(dtCourse.Rows[n]["studyHours"].ToString());
                        intTotalTimeWeightA = int.Parse(dtRuleList.Rows[0]["TotalTimeWeightA"].ToString());
                        //TotalTime_Low = int.Parse(dtRuleList.Rows[0]["TotalTime_Low"].ToString());
                        //TotalTime_High = int.Parse(dtRuleList.Rows[0]["TotalTime_High"].ToString());
                        TotalTime_Low = double.Parse(dtRuleList.Rows[0]["TotalTimeWeightA"].ToString())*3600;  //此处需要换算成秒来计算
                        TotalTime_High = double.Parse(dtRuleList.Rows[0]["TotalTime_High"].ToString())*3600;
                        intScoresHours = 0;

                        if (intHours < TotalTime_High && intHours > TotalTime_Low && TotalTime_High>0)
                        {
                            intScoresHours = intHours / TotalTime_High;
                        }
                        else if (intHours >= TotalTime_High && TotalTime_High > 0)
                        {
                            intScoresHours = 1; //int.Parse(strCourseIDB[1]);
                        }
                        else
                        {
                            intScoresHours = 0;
                        }
                    }
                    if (dtWorkNum.Rows.Count > 0 && dtRuleList.Rows.Count > 0)
                    {
                        //计算作业完成次数得分
                        intworkFinishTimes = int.Parse(dtWorkNum.Rows[n]["WorkNum"].ToString());
                        intFinishTimesWeightB = int.Parse(dtRuleList.Rows[0]["WorkFinishTimesWeightB"].ToString());
                        WorkFinishTimes_Low = int.Parse(dtRuleList.Rows[0]["WorkFinishTimes_Low"].ToString());
                        intWorkScores = 0;
                        WorkFinishTimes_High = int.Parse(dtRuleList.Rows[0]["WorkFinishTimes_High"].ToString());

                        if (intworkFinishTimes < WorkFinishTimes_High && intworkFinishTimes > WorkFinishTimes_Low && WorkFinishTimes_High>0)
                        {
                            intWorkScores = intworkFinishTimes / WorkFinishTimes_High;
                        }
                        else if (intworkFinishTimes >= WorkFinishTimes_High && WorkFinishTimes_High > 0)
                        {
                            intWorkScores = 1;
                        }
                        else
                        {
                            intWorkScores = 0;
                        }
                    }
                    if (dtTasksReply.Rows.Count > 0 && dtRuleList.Rows.Count > 0)
                    {
                        //计算作业提交次数得分
                        intTasksReply = int.Parse(dtTasksReply.Rows[n]["ReplyNum"].ToString());
                        workCommentTimesWeightB = int.Parse(dtRuleList.Rows[0]["workCommentTimesWeightB"].ToString());
                        WorkCommentTimes_Low = int.Parse(dtRuleList.Rows[0]["WorkCommentTimes_Low"].ToString());
                        WorkCommentTimes_High = int.Parse(dtRuleList.Rows[0]["WorkCommentTimes_High"].ToString());
                        intScoresComment = 0;

                        if (intTasksReply < WorkCommentTimes_High && intTasksReply > WorkCommentTimes_Low && WorkCommentTimes_High>0)
                        {
                            intScoresComment = intTasksReply / WorkCommentTimes_High;
                        }
                        else if (intTasksReply >= WorkCommentTimes_High && WorkCommentTimes_High > 0)
                        {
                            intScoresComment = 1;
                        }
                        else
                        {
                            intScoresComment = 0;
                        }
                    }


                    if (dtExam.Rows.Count > 0 && dtRuleList.Rows.Count > 0)
                    {
                        //计算考试成绩得分
                        intworkTatolWeightA = int.Parse(dtRuleList.Rows[0]["WorkTatolWeigthA"].ToString());
                        intExam = int.Parse(dtExam.Rows[n]["UPHistoryScore"].ToString());
                        intScoreWeightA = int.Parse(dtRuleList.Rows[0]["ScoreWeightA"].ToString());
                        Score_Low = int.Parse(dtRuleList.Rows[0]["Score_Low"].ToString());
                        Score_High = int.Parse(dtRuleList.Rows[0]["Score_High"].ToString());
                        intScoresExam = 0;

                        if (intExam < Score_High && intExam > Score_Low && Score_High>0)
                        {
                            intScoresExam = intExam / Score_High;
                        }
                        else if (intExam >= Score_High && Score_High > 0)
                        {
                            intScoresExam = 1;
                        }
                        else
                        {
                            intScoresExam = 0;
                        }
                    }
                    //计算每个学员每门课的学分（百分比）
                    intscoresStuCou = intScoresHours * (intTotalTimeWeightA / 100) + ((intWorkScores * (intFinishTimesWeightB / 100)) + (intScoresComment * (workCommentTimesWeightB / 100))) * intworkTatolWeightA + (intScoresExam * (intScoreWeightA / 100));
                    //学员学分
                    if (intscoresStuCou >= int.Parse(strCourseIDB[1]) && dtCourseInfo.Rows.Count > 0)
                    {
                        //确保该课程设置了学分
                        int intCourseScoreA = 0;
                        if (dtCourseInfo.Rows.Count > 0)
                        {
                            if (!string.IsNullOrEmpty(dtCourseInfo.Rows[0]["Score"].ToString()))
                            {
                                intCourseScoreA = int.Parse(dtCourseInfo.Rows[0]["Score"].ToString());
                            }
                        }
                        douScoreP = (intscoresStuCou / 100) * intCourseScoreA;
                    }
                    else
                    {
                        douScoreP = 0;
                    }
                    //计算每个学员的总学分
                    intscoresStu = intscoresStu + douScoreP;
                }
                //计算每个班级的总学分
                intScoresCls = intScoresCls + intscoresStu;
            }
            //计算班级平均分
            if (dtUser.Rows.Count > 0)
            {
                douAvgScoresCls = intScoresCls / dtUser.Rows.Count;
            }
            dt.Rows[i]["Batch"] = strBatch;
            dt.Rows[i]["avgScore"] = douAvgScoresCls.ToString("#0.00");//.ToString();
            if (dt.Rows[i]["Broswer"].ToString() == "True")
                dt.Rows[i]["StrState"] = "允许";
            else
                dt.Rows[i]["StrState"] = "不允许";
        }
        //排名
        int sng = 2;
        DataView dv = dt.DefaultView;
        if (dt.Rows.Count > 0)
        {
            dv.Sort = "Batch ,avgScore desc";
            dt = dv.ToTable();
            dt.Rows[0]["levelClass"] = 1;
            for (int j = 1; j < dt.Rows.Count; j++)
            {
                if (dt.Rows[j]["Batch"].Equals(dt.Rows[j - 1]["Batch"]))
                {
                    dt.Rows[j]["levelClass"] = sng;
                    sng++;
                }
                else
                {
                    dt.Rows[j]["levelClass"] = 1;
                    sng = 2;
                }
            }
        }
        rptNew.DataSource = dt;
        rptNew.DataBind();
        PreAspNetPager(AspNetPager1);
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string search = GetSearch();
        BinderPager(search);
        BinderPG(search, 1);
    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        string search = GetSearch();
        BinderPG(search, AspNetPager1.CurrentPageIndex);
    }

    protected void rptNew_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "sturank")
        {
            string url = "StudentRank.aspx?CID=" + e.CommandArgument.ToString();
            Script.RedirectURL(url);

        }
    }
}
